<?php 
if(!defined('IN_OPEN')) exit('no access');
if(!defined('OPEN_ROOT')) define('OPEN_ROOT',dirname(dirname(dirname(__FILE__))));
require_once OPEN_ROOT.'/lib/class/db.class.php';
require_once OPEN_ROOT.'/lib/class/memcached.class.php';
require_once OPEN_ROOT.'/lib/class/score.class.php';
require_ONCE OPEN_ROOT.'/lib/function/core.func.php';
class app
{
	public function __construct()
	{
		if(empty($oauth_dbhost)) include  OPEN_ROOT.'/config.inc.php';
		$this->db = db::connect($oauth_dbhost,$oauth_dbuser,$oauth_dbpw,$oauth_dbname);
		$this->mem = new Memcached();
		//var_dump($oauth_dbhost);
	}
	public function getAppInfoByName($appname,$cacheflag=true)
	{
		$cachekey = md5($appname.'_appinfo_appname');
		$info = $this->mem->get($cachekey);
		if($info==false || $cacheflag==false)
		{
			$sql ="select * from tyopen_application where appname='".mysql_escape_string($appname)."'";
			$info = $this->db->fetchOne($sql);
			$this->mem->set($cachekey,$info,3600);
		}
		return $info;
	}
	public function getAppInfoById($appid,$cacheflag=true)
	{
		$cachekey = md5($appid.'_appinfo_appid');
		$info = $this->mem->get($cachekey);
		//$info = false;
		if($info==false || $cacheflag==false)
		{
			$sql ="select a.id as appid,a.appname,a.appurl,a.iconurl as imgurl,a.status,a.ownerid,a.type as typeid,a.ownername,a.intro,b.typename from tyopen_application as a left join tyopen_apptype as b on a.type=b.typeid where a.id=".mysql_escape_string($appid);
			$info = $this->db->fetchOne($sql);
			$this->mem->set($cachekey,$info,3600);
		}
		return $info;
	}
	/**
	 * 获取app应用的缩略图
	 */
	public function getAppThumb($appid,$cacheflag=true)
	{
		$appid = intval($appid);
		$cachekey = md5($appid.'_appthumplist');
		$imglist = $this->mem->get($cachekey);
		if($imglist==false || $cacheflag==false)
		{
			$sql = "select imgurl,bigurl from tyopen_appthumb where appid=$appid order by createtime desc";
			$imglist = $this->db->fetchAll($sql);
			$this->mem->set($cachekey,$imglist,86400);
		}
		return $imglist;
	}
	/**
	 * 按分类获取applist
	 */
	public function getAppList($typeid,$cacheflag=true)
	{
		$typeid = intval($typeid);
		$cachekey = md5($typeid.'_applist');
		$applist = $this->mem->get($cachekey);
		//var_dump($applist);
		if($applist==false || $cacheflag==false)
		{
			$sql = "select a.id as appid,a.appname,a.iconurl as imgurl,a.ownerid,a.ownername,a.intro,a.tag,b.typename,group_concat(c.tagname) as tags from tyopen_application as a left join tyopen_apptype as b on a.type=b.typeid left join tyopen_taglist as c on a.id=c.appid where a.type=$typeid and a.status in(2,3,4) group by c.appid order by a.createtime desc";
			if($_GET['debug']) echo $sql;
			$applist = $this->db->fetchAll($sql);
			if($applist === false) return false;
			foreach($applist as $key=>$value)
  			{	
		    $scoreOBJ = new appscore($value['appid']);
		    $Score = intval( $scoreOBJ-> getAverageScore() );
		    //var_dump($Score);
		    $w = 20 * $Score;
		    $applist[$key]['avgScore'] = $Score;
		    $applist[$key]['width'] = $w;

  			}
			$this->mem->set($cachekey, $applist, 3600);
		}
		//$this->mem->set($cachekey, $applist, 6);
		return $applist;
	}
	/**
	 * 取作者的应用及评分
	 */
	public function getAuthorAppList($tyid,$cacheflag=true)
	{
		$tyid = intval($tyid);
		$cachekey = md5($tyid.'_authorapplist');
		$list = $this->mem->get($cachekey);
		if($list==false || $cacheflag==false)
		{
			$sql = "select a.appname,a.id as appid,avg(b.score) as averagescore from tyopen_application as a  left join tyopen_appscore as b on a.id=b.appid where a.ownerid=$tyid  and a.status in(2,3,4) group by a.id";
			$list = $this->db->fetchAll($sql);
			//print_r($list);
			$this->mem->set($cachekey,$list,3600);
		}
		return $list;
	}
	public function getHotAppList($limit=6,$cacheflag=true)
	{
		$cachekey = md5($limit.'app_hotlist');
		$applist = $this->mem->get($cachekey);
		if($applist==false || $cacheflag==false)
		{
			$sql = "select sum(a.count) as weekcount ,a.param as appid,b.type as typeid,b.intro,b.appname,b.iconurl as imgurl,b.ownerid,b.ownername,c.typename from tyopen_count as a left join tyopen_application as b  on a.param=b.id left join tyopen_apptype as c on b.type=c.typeid where a.type='appusercount'  and b.type!=8 and  b.status in(2,3,4) and date(a.createtime)>=DATE_SUB(CURDATE(), INTERVAL 7 DAY) group by a.param order by weekcount desc limit $limit";
			$applist = $this->db->fetchAll($sql);
			if($applist==false) return false;
			$this->mem->set($cachekey,$applist,3600);
		}
		return $applist;
	}
	/**
	 * 获取最新APP
	 * @param $limit 取APP应用个数，默认为6
	 * @param $cacheflag 是否从缓存读取
	 */
	public function getNewAppList($limit=6,$cacheflag=true)
	{
		$cachekey = md5($limit.'app_newlist');
		$applist = $this->mem->get($cachekey);
		if($applist==false || $cacheflag==false)
		{
			$sql = "select a.id as appid,a.type as typeid,a.appname,a.intro,a.iconurl as imgurl,a.ownerid,a.ownername,b.typename  from tyopen_application as a left join tyopen_apptype as b on a.type=b.typeid where  a.status in(2,3,4) and a.type!=8 order by a.lastupdate desc limit $limit";
			$applist = $this->db->fetchAll($sql);
			if($applist==false) return false;
			$this->mem->set($cachekey,$applist,3600);
		}
		return $applist;
	}
	/**
	 * 获取所有APP分类统计数
	 */
	public function getTypeCount($cacheflag=true)
	{
		$cachekey = md5('apps.tianya.cn_typecountlist');
		$result = $this->mem->get($cachekey);
		//echo "<br>cache<br>";
		//print_r($result);
		if($result==false || $cacheflag==false)
		{
			$sql ="select count(id) as appcount,type as typeid from tyopen_application where status in(2,3,4) group by type";
			$result = $this->db->fetchAll($sql,'typeid');
			$this->mem->set($cachekey,$result,3600);
		}
		return $result;
	}
	/**
	 * 搜索应用
	 */
	public function search($key,$cacheflag=true)
	{
		$cachekey = md5($key.'app_searchlist');
		$applist = $this->mem->get($cachekey);
		if($applist==false || $cacheflag==false)
		{
			$key = post_check($key);
			$sql = "select a.id as appid,a.type as typeid,a.appname,a.intro,a.iconurl as imgurl,a.ownerid,a.ownername,b.typename,group_concat(c.tagname) as tags  from tyopen_application as a left join tyopen_apptype as b on a.type=b.typeid left join tyopen_taglist as c on a.id=c.appid where  a.status in(2,3,4) and concat(a.appname,a.tag) like '%".mysql_escape_string($key)."%' group by c.appid order by a.lastupdate desc ";
			$applist = $this->db->fetchAll($sql);
			if($applist==false) return false;
			$this->mem->set($cachekey,$applist,3600);
		}
		return $applist;
	}
	/**
	 * 获取APP应用使用的用户
	 */
	public function getappuser($appid,$cacheflag = true)
	{
		$cachekey = md5($appid.'_appuserlist');
		$userlist = $this->mem->get($cachekey);
		if($userlist==false || $cacheflag==false)
		{
			$sql = "select tyid from app_setting where appid=".intval($appid);
			$userlist = $this->db->fetchAll($sql);
			foreach ($userlist as $user)
			{
				$list[] = $user['tyid'];
			}
			$userlist = $list;
			$this->mem->set($cachekey,$userlist,3600);
		}
		return $userlist;
	}
	/**
	 * 增加导航操作
	 */
	public function addshow($tyid,$type,$appids)
	{
		 if(empty($appids) || empty($tyid)) return false;
		    //print_r($tags);
			$sqladd = '';
			if(is_array($appids))
			{
				$appids = array_unique($appids);
				$appids = array_filter($appids);
				foreach($appids as $key=>$appid)
				{
					if($key==0) 
					{
						$sqladd.= "($tyid,'$type',$appid)";
						
					}
					else 
					{
						$sqladd.= ",($tyid,'$type',$appid)";
						
					}
				}
			}
			else
			{
				$sqladd.= "($tyid,'$type',$appids)";
				
			}
			$sql = "insert ignore into app_setting(tyid,type,appid) values".$sqladd;
			//echo "<br>".$sql;
			$result = $this->db->query($sql);
			if($result==false) return false;
			$cachekey = md5($tyid.$type.'_mytianya');
			if($type=='myallapp') $applist = $this->getuserapp($tyid,false);
			else $applist = $this->getmyapp($tyid,$type,false);
			return $result;
	}
	
	public function delshow($tyid,$type,$appids)
	{
		if(empty($appids) || empty($tyid)) return false;
		$i=0;
		$str ='';
		if(is_array($appids))
		{
			foreach ($appids as $appid)
			{
				$appid = intval($appid);
				if($i==0) $str.="'$appid'";
				else $str.=",'$appid'";
				$i++;
			}
			//echo $str;
			$sql = "delete from app_setting where tyid=$tyid and type ='$type' and appid in ($str)";
		}
		else 
		{
			$appid = intval($appids);
			$sql = "delete from app_setting where tyid=$tyid and type ='$type' and appid=$appid";
		}
		$result = $this->db->query($sql);	
		if($result==false) return false;
		$cachekey = md5($tyid.$type.'_mytianya');
		if($type=='myallapp') $applist = $this->getuserapp($tyid,false);
		else $applist = $this->getmyapp($tyid,$type,false);
		return $result;
	}
	public function getmyapp($tyid,$type,$cacheflag=true)
	{
		$cachekey = md5($tyid.$type.'_mytianya');
		$applist =  $this->mem->get($cachekey);
		if($applist==false || $cacheflag==false)
		{
			$sql = "select a.*,b.id,b.appname,b.iconurl as appimg from  app_setting as a left join tyopen_application as b on a.appid=b.id  where a.type='$type' and  a.tyid=".intval($tyid);
			$applist = $this->db->fetchAll($sql);
			$this->mem->set($cachekey,$applist,86400);
		}
		return $applist;
	}
	public function gettopapp($tyid,$cacheflag=true)
	{
		$cachekey = md5('mytianya_topapp');
		$applist = $this->mem->get($cachekey);
		if($applist==false || $cacheflag==false)
		{
			$sql = "select a.*,b.id,b.appname from  app_setting as a left join tyopen_application as b on a.appid=b.id  where a.type='top' and  a.tyid=1";
			$applist = $this->db->fetchAll($sql);
			$this->mem->set($cachekey,$applist);
		}
		return $applist;
	}
	public function getuserapp($tyid,$cacheflag=true)
	{
		$cachekey = md5($tyid.'myallapp'.'_mytianya');
		$applist = $this->mem->get($cachekey);
		if($applist==false || $cacheflag==false)
		{
			$wheresql = ' ';
			$sql = "select appid,
			b.appname, b.iconurl as appimg
			from app_setting as a  
			left join tyopen_application as b 
			on a.appid = b.id 
			where a.tyid=$tyid and a.type='myallapp' order by a.createtime desc";
			$applist = $this->db->fetchAll($sql);
			$this->mem->set($cachekey,$applist,86400);
		}
		return $applist;
	}
	/**
	 * 删除授权
	 */
	public function deltoken($tyid,$appid)
	{
		$tyid = intval($tyid);
		$appid = intval($appid);
		$sql = "delete from oauth_server_token where ost_usa_id_ref=".mysql_escape_string($tyid)." and ost_osr_id_ref=".mysql_escape_string($appid);
		$result = $this->db->query($sql);
		$cachekey = md5($tyid.'_myapp');
		$applist = $this->getuserapp($tyid,false);
		return $result;
	}
	public function getallapp($status=null,$cacheflag=true)
	{
		$cachekey = md5($status.'_allapp');
		if(!empty($status)) $where = "in ($status)";
		else $where='1=1';
		$applist = $this->mem->get($cachekey);
		if($applist==false || $cacheflag==false)
		{
			$sql ="select * from tyopen_application where $where order by createtime desc";
			$applist = $this->db->fetchAll($sql);
			$this->mem->set($cachekey,$applist);
		}
		return $applist;
		
	}


   	public function getOtherInfo($appID, $ownerID, $cacheflag=true)
    {

        //$appInfo = $this->getAppInfoById($appID);
        //var_dump($appInfo);
    	$cachekey = md5($appID . 'tyopen_application' . '_appother');
		$appOther = $this->mem->get($cachekey);
    	if($appOther==false || $cacheflag==false)
		{
            //$db_user_app = db::connect($oauth_dbhost, $oauth_dbuser, $oauth_dbpw, $oauth_dbname);
          $sql = "SELECT * FROM tyopen_application WHERE status in(2,3,4) and ownerid = " . $ownerID ." and id != " . $appID . " limit 4";
          if($_GET['debug']) echo $sql;
            $appOther =  $this->db->fetchAll($sql);
            //var_dump($appOther);
            foreach($appOther as $key=>$value)
            {
                        //var_dump($value); 
                $scoreOBJ = new appscore($value['id']);
                $Score = $scoreOBJ-> getAverageScore();
                $w = 20 * $Score;
                $appOther[$key]['avgScore'] = $Score;
                $appOther[$key]['width'] = $w;

            }
            $this->mem->set($cachekey,$appOther,86400);

        }
        //var_dump($appOther);
        return $appOther;
    }	
    public function getAppOwnerInfo($tyid,$cacheflag=true)
	{
		$cachekey = md5($tyid . 'tyopen_application' . 'AppOwnerInfo');
		$applist = $this->mem->get($cachekey);
		if($applist==false || $cacheflag==false)
		{
			$sql = "SELECT `id` , `appname`, `iconurl` FROM tyopen_application WHERE ownerid=$tyid AND status in(2,3,4) ORDER BY createtime DESC";
			$applist = $this->db->fetchAll($sql);
			$this->mem->set($cachekey,$applist,86400);
		}
		return $applist;
    }	
	
}
?>
